<script setup>
// 导入教练相关的API接口模块，里面封装了与后端交互的方法
import coachApi from '@/api/coachApi.js'
// 导入Vue3的响应式数据相关函数：reactive用于创建响应式对象，ref用于创建响应式基本类型或引用类型
import {reactive,ref} from 'vue'
// 导入Element Plus的消息提示组件
import {ElMessage,ElMessageBox} from 'element-plus'
// 创建一个响应式引用类型变量coachs，用于存储教练列表数据，初始值为空数组

const baseURL = 'http://localhost:9001'

const coachs = ref([])
// 创建一个响应式对象pageInfo，用于管理分页信息
const pageInfo = reactive({
    page:1,
    limit:10,
    total:0
})
// 页面加载时立即调用函数，加载教练列表数据
loadCoachs()
// 定义加载教练列表的函数
function loadCoachs(){
    // 调用coachApi的search方法，传入分页信息pageInfo作为查询参数
    coachApi.search(pageInfo).then(result=>{
        // 请求成功后的处理（后端接口返回成功）
        if(result.code == 200) {
            console.log('result:',result)
            coachs.value = result.data.list
            pageInfo.total = result.data.total
        }
    }).catch(error=>{
        //请求后端接口失败
        // ElMessage.error(error)
    })
}
// 定义一个响应式变量，控制新增教练弹窗的显示/隐藏，初始为false（隐藏）
const addVisible = ref(false)
// 定义一个响应式对象，存储新增教练的表单数据（如姓名、电话等），初始为空对象
const addCoach = ref({})
// 显示添加教练的弹框：将addVisible设为true，控制弹窗显示
function showAdd() {
    addVisible.value = true
}

// 添加教练
function handleAdd() {
    coachApi.add(addCoach.value).then(result=>{
        if(result.code == 200) {
            addVisible.value = false        // 关闭添加弹框
            addCoach.value = ref({})        // 清空弹框中的数据
            loadCoachs()        // 重新加载教练员列表
            ElMessage.success('添加成功')
        } else{
            addVisible.value = false
            addCoach.value = ref({})        // 清空弹框中的数据
            ElMessage.error(result.msg)
        }
    }).catch(error=>{
        ElMessage.error(error)
    })
}

const editVisible = ref(false)
const editCoach = ref({})
// 显示编辑弹出框
function showEdit(row) {
    editVisible.value = true
    console.log('教练信息:',row)
    editCoach.value = row
}
// 确认修改
function handleEdit() {
    coachApi.edit(editCoach.value).then(result=>{
        if (result.code == 200) {
            // 修改成功
            editVisible.value = false
            ElMessage.success('恭喜，修改成功')
            loadCoachs()
        } else {
            // 修改失败
            editVisible.value = false
            ElMessage.error(result.msg)
            loadCoachs()
        }
    }).catch(error=>{
        // 修改失败
        editVisible.value = false
        ElMessage.error('服务器忙，请稍后再试')
    })
}

// 删除
function handleRemove(row) {
    console.log("row1:"+row.id)
    ElMessageBox.confirm(
        '您确定要删除这条教练信息吗?',
        '删除教练',
        {
            confirmButtonText:'确定',
            cancelButtonText:'取消',
        }
    ).then(()=>{
        // 点击确认
        //ElMessage.success(row)
        console.log("row2:"+row.id)
        coachApi.remove(row.id).then(result=>{
            //交互成功
            if(result.code == 200) {
                ElMessage.success('删除成功')
                loadCoachs()
            } else {
                ElMessage.error(result.msg)
                loadCoachs()
            }
        }).catch(error=>{
            //点击取消
            ElMessage.error(error)
        })
    }).catch(()=>{
        // 点击取消
    })
}

// 预留方法：根据图片路径获取图片URL（用于显示已上传的教练照片）
function getImgUrl(photo) {
    return photo
}
// 预留方法：获取文件上传的后端接口地址
function getUploadURL(){
    return baseURL + "/upload/savePic"
}
function handleAddAvatarSuccess(res){// 应该是上传的返回结果能自动注入把
    console.log(res.data)
    addCoach.value.photo = res.data
    console.log(addCoach.value.photo)
}
function handleEditAvatarSuccess(res){// 应该是上传的返回结果能自动注入把
    console.log(res.data)
    editCoach.value.photo = res.data
    console.log(editCoach.value.photo)
}

// 教练模糊查询
function onSearch() {
    pageInfo.page = 1
    loadCoachs()
}
</script>

<template>
    <div class="content">
        <!-- 搜索栏 -->
        <el-form :model="pageInfo" :inline="true">
            <el-form-item label="姓名" :label-width="60">
                <el-input v-model="pageInfo.name" clearable placeholder="请输入教练名字"/>
            </el-form-item>
            <el-form-item label="手机号" :label-width="60">
                <el-input v-model="pageInfo.phone" clearable placeholder="请输入教练手机"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch"><el-icon><Search></Search></el-icon></el-button>
            </el-form-item>
        </el-form>
        <!-- 新增教练按钮 -->
        <div class="bar">
            <el-button type="success" @click="showAdd" >创建教练</el-button>
        </div>
        <!-- 列表 -->
        <el-table :data="coachs" :stripe="true" :border="true" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="photo" label="照片" >
                <template #default="scope">
                    <img :src="getImgUrl(scope.row.photo)" style="max-height: 60px; max-width: 120px;"/>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="phone" label="手机号" width="180" />
            <el-table-column prop="wechat" label="微信" />
            <el-table-column prop="recomm" label="简介" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="success"
                        @click="showEdit(scope.row)">编辑</el-button> 
                    <el-button size="small" type="danger"
                        @click="handleRemove(scope.row)">删除</el-button> 
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
            :total="pageInfo.total" :page-sizes="[10, 20, 50, 100]" :background="true"
            layout="total, sizes, prev, pager, next, jumper" @change="loadCoachs" />
    </div>

    <!-- 添加的弹窗 -->
    <!-- v-model="控制弹窗显示/隐藏" -->
    <el-dialog v-model="addVisible" title="创建新教练" width="500">
        <!-- :model="表单数据绑定到addCoach对象(双向绑定)" -->
        <el-form :model="addCoach">
            <!-- 照片上传表单项 -->
            <el-form-item label="照片" :label-width="60">
                <!-- 
                :action="上传文件的后端接口地址（调用getUploadURL方法获取）"
                :show-file-list="false"：不显示已上传文件列表
                :on-success="handleAddAvatarSuccess"：上传成功后的回调方法（需另行定义） -->
                <el-upload
                    class="avatar-uploader"
                    :action="getUploadURL()"
                    :show-file-list="false"
                    :on-success="handleAddAvatarSuccess"
                >
                    <!-- 
                    v-if="addCoach.photo"：如果addCoach有photo属性（已上传），则显示图片
                    :src="getImgUrl(addCoach.photo)"：调用getImgUrl方法获取图片完整路径 -->
                    <img v-if="addCoach.photo" :src="getImgUrl(addCoach.photo)" class="avatar" />
                    <!-- 未上传时显示的图标：
                    v-else：未上传时显示
                    Plus：Element Plus的“加号”图标（需导入） -->
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="名字" :label-width="60">
                <!-- v-model="addCoach.name"：双向绑定到addCoach的name属性; placeholder：提示文本 -->
                <el-input v-model="addCoach.name" placeholder="请输入教练名字"/>
            </el-form-item>
            <el-form-item label="电话" :label-width="60">
                <el-input v-model="addCoach.phone" placeholder="请输入教练电话"/>
            </el-form-item>
            <el-form-item label="微信" :label-width="60">
                <el-input v-model="addCoach.wechat" placeholder="请输入教练微信"/>
            </el-form-item>
            <!-- 简介输入框（多行文本）-->
            <el-form-item label="简介" :label-width="60">
                <el-input
                    :rows = "5"
                    maxlength="255" 
                    placeholder="请输入教练简介"
                    show-word-limit
                    type="textarea"
                    v-model="addCoach.recomm"
                    autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">
                    创建
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 编辑的弹窗 -->
    <el-dialog v-model="editVisible" title="编辑教练" width="500">
        <el-form :model="editCoach">
            <el-form-item label="照片" :label-width="60">
                <el-upload
                    class="avatar-uploader"
                    :action="getUploadURL()"
                    :show-file-list="false"
                    :on-success="handleEditAvatarSuccess"
                >
                    <img v-if="editCoach.photo" :src="getImgUrl(editCoach.photo)" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="名字" :label-width="60">
                <el-input v-model="editCoach.name" placeholder="请输入教练名字"/>
            </el-form-item>
            <el-form-item label="电话" :label-width="60">
                <el-input v-model="editCoach.phone" placeholder="请输入教练电话"/>
            </el-form-item>
            <el-form-item label="微信" :label-width="60">
                <el-input v-model="editCoach.wechat" placeholder="请输入教练微信"/>
            </el-form-item>
            <el-form-item label="简介" :label-width="60">
                <el-input
                    :rows = "5"
                    maxlength="255"
                    placeholder="请输入教练简介"
                    show-word-limit
                    type="textarea"
                    v-model="editCoach.recomm"
                    autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="editVisible = false">取消</el-button>
                <el-button type="primary" @click="handleEdit">
                    编辑
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style >

</style>